const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('./utils/log4j')
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const koajwt = require('koa-jwt')
const util = require('./utils/util')
const users = require('./routes/users')
const menus = require('./routes/menus')
const mbrs = require('./routes/mbrs');
const roles = require('./routes/roles')
const depts = require('./routes/depts');
const rbs = require('./routes/rbs');
const userLogins = require('./routes/userLogins')
const uploadRds = require('./routes/uploadRds')
const reviews = require('./routes/reviews')
const reviewRecords = require('./routes/reviewRecords')
const rbArchives = require('./routes/rbArchives')

// error handler
onerror(app)

require('./config/db')

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))


// logger
app.use(async (ctx, next) => {
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)

  await next().catch((err)=>{
    ctx.status = 200;
    if(err.status == '401'){
      ctx.body = util.fail('Token认证失败', util.CODE.AUTH_ERROR)
    }else{
      throw err;
    }
  })
})

app.use(koajwt({secret:'zufe'}).unless({
  path: [/^\/api\/users\/login/, /^\/api\/upload\/download/]
}))//一个中间件

router.prefix("/api")


router.use(users.routes(), users.allowedMethods())
router.use(menus.routes(), menus.allowedMethods())
router.use(mbrs.routes(), mbrs.allowedMethods())
router.use(roles.routes(), roles.allowedMethods())
router.use(depts.routes(), depts.allowedMethods())
router.use(rbs.routes(), rbs.allowedMethods())
router.use(uploadRds.routes(), uploadRds.allowedMethods())
router.use(userLogins.routes(), userLogins.allowedMethods())
router.use(reviews.routes(), reviews.allowedMethods())
router.use(reviewRecords.routes(), reviewRecords.allowedMethods())
router.use(rbArchives.routes(), rbArchives.allowedMethods())

app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  log4js.error(`${err.stack}`)
});

module.exports = app
